<template>
	<view class="user-coupon-list" :style="{background:pageColor}">
		<fixed :zIndex="999">
			<view class="fill-base flex-center pd-lg" v-if="configInfo.plugAuth.store">
				<view class="flex-1">
					<search @input="toSearch" type="input" :padding="0" :radius="30" height="70rpx" background="#F0F0F0"
						placeholder="搜索限用门店">
					</search>
				</view>
				<view @tap.stop="$refs.search_item.open()" class="flex-y-center pl-lg">筛选<i
						class="iconfont iconshaixuanxia-1 c-caption"></i></view>
			</view>
			<view v-else>
				<tab @change="handerTabChange" :list="tabList" :activeIndex="activeIndex*1" :activeColor="primaryColor"
					width="20%" height="100rpx"></tab>
				<view class="b-1px-b"></view>
			</view>
		</fixed>

		<block v-for="(item,index) in list.data" :key="index">
			<view @tap.stop="goDetail(index)" class="list-item rel fill-base" v-if="[1,2].includes(item.status)">
				<view class="bg abs" :style="{background:primaryColor}" v-if="item.status==1"></view>
				<view class="flex-center rel" style="z-index: 2;">
					<view class="item-title flex-center c-base abs" :class="[{'underline':item.use_scene}]">
						{{item.use_scene==1?'线下核销':'线上抵扣'}}
					</view>
					<view class="item-status flex-center c-base abs" :style="{color:primaryColor}"
						v-if="item.status==1">
						<view class="bg abs" :style="{background:primaryColor}"></view>
						待使用
					</view>
					<i class="iconfont item-icon iconyishiyong abs" :style="{color:primaryColor}"
						v-if="item.status == 2"></i>
					<view class="item-price flex-center flex-column c-base rel"
						:style="{background:`linear-gradient( 180deg, ${color} 0%, ${primaryColor} 100%)`}">
						<view class="dot-item abs fill-base radius left"></view>
						<view class="dot-item abs fill-base radius right"></view>
						<view class="flex-y-baseline f-sm-title text-bold">¥<view style="font-size:48rpx">
								{{item.discount}}
							</view>
						</view>
						<view class="mt-sm f-icontext">{{item.type==0?`满${item.full}元可用`:'无门槛'}}</view>
					</view>
					<view class="flex-1 ml-lg" style="color:#1F1F1F">
						<view class="f-mini-title c-title text-bold ellipsis"
							:class="[{'max-400':item.status==1},{'max-450':item.status!=1}]" style="margin: 5rpx 0;">
							{{item.title}}
						</view>
						<view class="flex-between pr-lg">
							<view>
								<view class="f-icontext">共{{item.num}}张</view>
								<view class="flex-y-center f-icontext">有效期至<view style="margin-left: 14rpx;">
										{{item.start_time.split(" - ")[1]}}
									</view>
								</view>
								<view class="flex-y-center f-ms-little mt-sm" style="color: #ADADAD;">使用规则<i
										class="iconfont iconxiangxiazhankai"></i>
								</view>
							</view>
							<view v-if="item.status==1">
								<view @tap.stop="toUse(index)" class="use-btn flex-center f-caption c-base radius"
									:style="{background:primaryColor}">
									{{item.use_scene?`去核销`:`去使用`}}
								</view>
								<block v-if="item.can_gift">
									<!-- #ifdef MP-WEIXIN -->
									<button @tap.stop="()=>{}" open-type="share" :data-id="item.id" :data-index="index"
										class="can-gift clear-btn flex-center f-caption" :style="{color:primaryColor}"
										v-if="item.num==1">转赠好友
									</button>
									<view @tap.stop="toShare(index)" class="can-gift flex-center f-caption"
										:style="{color:primaryColor}" v-else>转赠好友
									</view>
									<!-- #endif -->
									<!-- #ifndef MP-WEIXIN -->
									<view @tap.stop="toShare(index)" class="can-gift flex-center f-caption"
										:style="{color:primaryColor}">转赠好友
									</view>
									<!-- #endif -->
								</block>
							</view>
						</view>
					</view>
				</view>
			</view>
			<movable-area @tap.stop="goDetail(index)" class="movable-area" v-else>
				<movable-view direction="horizontal" class="movable-view fill-base rel">
					<view class="touch-item" @touchstart="touchstart" @touchmove="touchmove"
						:class="[{'touch-move-active':item.isTouchMove}]" :data-index="index">
						<view class="list-item flex-center rel">
							<view class="item-title flex-center c-base abs" :style="{background:'#AFAFAF'}">
								{{item.use_scene==1?'线下核销':'线上抵扣'}}
							</view>
							<view class="item-status flex-center c-base abs" :style="{color:primaryColor}"
								v-if="item.status==-2">
								<view class="bg abs" :style="{background:primaryColor}"></view>
								已转赠
							</view>
							<i class="iconfont item-icon iconyishixiao abs" :style="{color:'#C4C5C8'}"
								v-if="item.status!=-2"></i>
							<view class="item-price flex-center flex-column c-base rel" :style="{background:`#D3D3D3`}">
								<view class="dot-item abs fill-base radius left"></view>
								<view class="dot-item abs fill-base radius right"></view>
								<view class="flex-y-baseline f-sm-title text-bold">¥<view style="font-size:48rpx">
										{{item.discount}}
									</view>
								</view>
								<view class="mt-sm f-icontext">{{item.type==0?`满${item.full}元可用`:'无门槛'}}</view>
							</view>
							<view class="flex-1 ml-lg" style="color:#1F1F1F">
								<view class="f-mini-title c-title text-bold max-450 ellipsis" style="margin: 5rpx 0;">
									{{item.title}}
								</view>
								<view class="pr-lg f-icontext">
									<view class="flex-y-center">
										<view>共{{item.num}}张</view>
										<view class="max-350 ellipsis ml-md" v-if="item.status==-2">
											获赠人：{{item.gift_user_name || '-'}}</view>
									</view>
									<view class="flex-y-center">有效期至<view style="margin-left: 14rpx;">
											{{item.start_time.split(" - ")[1]}}
										</view>
									</view>
								</view>
								<view class="flex-y-center f-ms-little mt-sm" style="color: #ADADAD;">使用规则<i
										class="iconfont iconxiangxiazhankai"></i>
								</view>
							</view>
						</view>
						<view @tap.stop="toDel(index)" class="delete-btn flex-center c-base">删除
						</view>
					</view>
				</movable-view>
			</movable-area>
		</block>

		<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading">
		</load-more>
		<abnor v-if="!loading&&list.data.length<=0&&list.current_page==1" type="COUPON" :isCenter="true"></abnor>

		<view class="space-footer"></view>


		<uni-popup @change="toChangePopupShow" ref="search_item" type="top" :custom="true" :zIndex="998">
			<view class="search-popup fill-base">
				<view style="height:130rpx"></view>
				<view class="title text-bold pt-lg mt-md">使用场景
				</view>
				<view class="flex-warp">
					<view @tap.stop="toChangeItem('use_scene',item.id)"
						class="search-item flex-center mt-md mr-md f-caption rel"
						:style="{color:check.use_scene==item.id?primaryColor:'#646464'}"
						v-for="(item,index) in typeList" :key="index">{{item.title}}
						<view class="search-item abs" :style="{background:primaryColor}"
							v-if="check.use_scene==item.id">
						</view>
					</view>
				</view>
				<view class="title text-bold pt-lg mt-md">卡券状态
				</view>
				<view class="flex-warp">
					<view @tap.stop="toChangeItem('status',item.id)"
						class="search-item flex-center mt-md mr-md f-caption rel"
						:style="{color:check.status==item.id?primaryColor:'#646464'}" v-for="(item,index) in tabList"
						:key="index">{{item.title}}
						<view class="search-item abs" :style="{background:primaryColor}" v-if="check.status==item.id">
						</view>
					</view>
				</view>
				<view style="height:60rpx"></view>
				<view class="flex-center">
					<view @tap.stop="toReset" class="search-btn flex-center f-mini-title c-title">重置
					</view>
					<view @tap.stop="toConfirm" class="search-btn flex-center ml-lg f-mini-title c-base"
						:style="{background:primaryColor,borderColor:primaryColor}">确定</view>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="share_coupon_item" type="center" :custom="true">
			<view class="common-popup-content fill-base pd-lg radius-34">
				<view class="title">转赠好友</view>
				<view class="desc">卡券持有人发起“转赠”后，获赠人需在24小时内确认接受，否则将视为转赠失败</view>
				<input v-model="shareForm.share_num" type="number"
					class="input pl-lg pr-lg text-center f-desc c-title mt-lg radius-20" placeholder="请输入转赠张数"
					placeholder-class="f-desc c-caption" />
				<view class="button">
					<view @tap.stop="$refs.share_coupon_item.close()" class="item-child">取消</view>
					<!-- #ifdef MP-WEIXIN -->
					<button @tap.stop="()=>{}" open-type="share" :data-id="shareForm.id" :data-num="shareForm.num"
						:data-share-num="shareForm.share_num" :data-index="shareForm.index" :data-popup="1"
						class="clear-btn item-child c-base" :style="{background: primaryColor,color:'#fff'}">确定</button>
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<view @tap.stop="toConfirmShare" class="item-child c-base"
						:style="{background: primaryColor,color:'#fff'}">确定</view>
					<!-- #endif -->
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex"
	export default {
		components: {},
		data() {
			return {
				options: {},
				typeList: [{
					title: '全部',
					id: -1
				}, {
					title: '线上抵扣',
					id: 0,
				}, {
					title: '线下核销',
					id: 1
				}],
				activeIndex: 0,
				tabList: [{
					title: '待使用',
					id: 1
				}, {
					title: '已使用',
					id: 2,
				}, {
					title: '已过期',
					id: 3
				}, {
					title: '已作废',
					id: 4
				}, {
					title: '已转赠',
					id: 5
				}],
				color: '',
				check: {
					use_scene: -1,
					status: 1
				},
				param: {
					page: 1,
				},
				list: {
					data: []
				},
				loading: true,
				lockTap: false,
				curInd: -1,
				startX: 0, //开始坐标
				startY: 0, //开始坐标
				shareForm: {
					id: 0,
					num: '',
					share_num: ''
				}
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
		}),
		onLoad(options) {
			let {
				tab = 0,
			} = options
			tab = tab * 1
			let {
				id
			} = this.tabList[tab]
			this.check.status = id
			this.param.status = id
			this.activeIndex = tab
			this.options = options
			// #ifdef MP-WEIXIN
			uni.hideShareMenu()
			// #endif
			this.initIndex()
		},
		onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif
			this.initRefresh()
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.param.page = this.param.page + 1;
			this.loading = true;
			this.getList();
		},
		async onShareAppMessage(e) {
			console.log(e, "====e")
			let {
				id: pid = 0
			} = this.userInfo
			let {
				id = 0,
					num = 1,
					shareNum = 1,
					popup = 0,
					index
			} = e.target.dataset
			let reg = /^[1-9]\d*$/
			if (!reg.test(shareNum) || shareNum * 1 > num * 1) {
				shareNum = !reg.test(shareNum) ? 1 : num
			}
			id = await this.$api.mine.couponGiftSend({
				coupon_id: id,
				num: shareNum
			})
			let path = `/user/pages/coupon/get-info?pid=${pid}&id=${id}`
			this.$util.log(path)
			if (num == shareNum) {
				this.list.data.splice(index, 1)
			} else {
				this.list.data[index].num = num - shareNum
			}
			if (popup) {
				this.$refs.share_coupon_item.close()
			}
			return {
				title: '我免费赠送了一张消费券给你，24小时后失效，赶紧领取吧！',
				imageUrl: 'https://api.huixuananmm.com/admin/anmo/coupon/share.png',
				path,
			}
		},
		methods: {
			...mapMutations(['']),
			async initIndex(refresh = false) {
				this.color = this.$util.rgbColor(this.primaryColor)
				await this.getList()
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				// #ifdef H5
				if (!refresh) {
					this.$jweixin.hideOptionMenu()
				}
				// #endif
			},
			initRefresh() {
				this.param.page = 1;
				this.param.use_scene = -1
				this.param.status = 1
				this.check = {
					use_scene: -1,
					status: 1
				}
				this.initIndex(true)
			},
			async getList() {
				let {
					list: oldList,
				} = this
				let param = this.$util.deepCopy(this.param)
				if (param.use_scene == -1) {
					delete param.use_scene
				}
				let newList = await this.$api.mine.userCouponList(param);
				newList.data.map(item => {
					item.isTouchMove = false
				})
				if (this.param.page == 1) {
					this.list = newList
				} else {
					newList.data = oldList.data.concat(newList.data)
					this.list = newList
				}
				this.loading = false
				this.$util.hideAll()
			},
			handerTabChange(index) {
				this.activeIndex = index
				let {
					id
				} = this.tabList[index]
				this.check.status = id
				this.param.status = id
				this.param.page = 1
				this.getList()
			},
			toSearch(val) {
				this.param.title = val
				let use_scene = val ? 1 : -1
				this.check.use_scene = use_scene
				this.param.use_scene = use_scene
				this.param.page = 1
				this.$refs.search_item.close()
				this.getList()
			},
			toChangeItem(key, id) {
				this.check[key] = id
			},
			toChangePopupShow(e) {
				let {
					show
				} = e
				if (show) return
				this.check = this.$util.pick(this.param, ['use_scene', 'status'])
			},
			toReset() {
				this.check = {
					use_scene: -1,
					status: 1
				}
				this.toConfirm()
			},
			toConfirm() {
				let param = Object.assign({}, this.param, this.check, {
					page: 1
				})
				this.param = param
				uni.pageScrollTo({
					scrollTop: 0
				})
				this.getList()
				this.$refs.search_item.close()
				this.popupTap = false
			},
			async toUse(index) {
				let {
					id,
					use_scene
				} = this.list.data[index]
				if (use_scene) {
					this.$util.goUrl({
						url: `/user/pages/coupon/detail?id=${id}`
					})
					return
				}
				this.$util.goUrl({
					url: `/pages/service`,
					openType: `reLaunch`
				})
			},
			async toDel(index) {
				let {
					id: coupon_id,
					status,
					gift_record_id = 0
				} = this.list.data[index]
				if (status == -2) {
					coupon_id = gift_record_id
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					let methodModel = status == -2 ? 'couponGiftDel' : 'couponDel'
					await this.$api.mine[methodModel]({
						coupon_id
					})
					this.$util.hideAll()
					this.$util.showToast({
						title: `删除成功`
					})
					this.list.data.splice(index, 1)
					this.lockTap = false
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			goDetail(index) {
				let {
					id,
					status,
					gift_record_id = 0
				} = this.list.data[index]
				let url = `/user/pages/coupon/detail?id=${id}`
				if (status == -2) {
					url += `&giftid=${gift_record_id}`
				}
				this.$util.goUrl({
					url
				})
			},
			toShare(index) {
				// #ifdef H5
				this.goDetail(index)
				return
				// #endif
				let {
					id,
					num
				} = this.list.data[index]
				this.shareForm = {
					id,
					num,
					share_num: num,
					index
				}
				if (num > 1) {
					this.$refs.share_coupon_item.open()
					return
				}
				this.toConfirmShare()
			},
			async toConfirmShare() {
				let {
					id,
					num,
					share_num,
					index
				} = this.shareForm
				let reg = /^[1-9]\d*$/
				if (!reg.test(share_num) || (share_num * 1 && share_num * 1 > num * 1)) {
					this.$util.showToast({
						title: !reg.test(share_num) ? `请输入正确的转赠张数` : `转赠张数不能大于${num}`
					})
					return
				}
				this.$util.showLoading()
				let data = await this.$api.mine.couponGiftSend({
					coupon_id: id,
					num: share_num
				})
				if (num == share_num) {
					this.list.data.splice(index, 1)
				} else {
					this.list.data[index].num = num - share_num
				}
				this.$util.hideAll()
				this.shareForm.id = data
				this.$refs.share_coupon_item.close()
				// #ifdef APP-PLUS
				this.toAppShare()
				// #endif
			},
			toAppShare() {
				let {
					id: pid = 0
				} = this.userInfo
				let {
					id
				} = this.shareForm
				let title = '我免费赠送了一张消费券给你'
				let summary = '24小时后失效，赶紧领取吧'
				let imageUrl = 'https://api.huixuananmm.com/admin/anmo/coupon/share-app.png'

				let {
					siteroot
				} = siteInfo
				let url = siteroot.split('/index.php')[0]
				let href = `${url}/${this.portName}/#/user/pages/coupon/get-info?id=${id}&pid=${pid}`

				// #ifdef APP-PLUS 
				let item = {
					href,
					title,
					summary,
					imageUrl,
				}
				if (this.configInfo.isIos) {
					this.$util.showLoading()
					this.toTransImg(item)
				} else {
					this.sharePage(item)
				}
				// #endif
			},
			toTransImg(item) {
				let that = this
				let cur_unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
				uni.downloadFile({
					url: item.imageUrl,
					success: (e) => {
						// 将png转换成jpg格式 只有jpg格式支持压缩api
						plus.zip.compressImage({
								src: e.tempFilePath,
								dst: `_doc/${cur_unix}.jpg`,
								format: "jpg"
							},
							response => {
								// 压缩图片
								plus.zip.compressImage({
									src: response.target,
									dst: `_doc/${cur_unix}-img.jpg`,
									quality: 50,
								}, res => {
									item.imageUrl = res.target || `/static/img/logo.png`
									that.sharePage(item)
								}, error => {
									item.imageUrl = `/static/img/logo.png`
									that.sharePage(item)
								})
							})
					}
				})
			},
			sharePage(item) {
				this.$util.hideAll()
				let {
					href,
					title,
					summary,
					imageUrl,
				} = item
				uni.share({
					provider: "weixin",
					scene: 'WXSceneSession',
					type: 0,
					href,
					title,
					summary,
					imageUrl,
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});
			},
			//手指触摸动作开始 记录起点X坐标
			touchstart(e) {
				//开始触摸时 重置所有删除
				this.list.data.forEach(item => {
					if (item.isTouchMove) //只操作为true的
						item.isTouchMove = false;
				})
				this.startX = e.changedTouches[0].clientX
				this.startY = e.changedTouches[0].clientY
			},
			//滑动事件处理
			touchmove(e) {
				let {
					startX,
					startY
				} = this
				let {
					index
				} = e.currentTarget.dataset //当前索引

				let {
					clientX,
					clientY
				} = e.changedTouches[0]
				let touchMoveX = clientX
				let touchMoveY = clientY
				//获取滑动角度
				let angle = this.angle({
					X: startX,
					Y: startY
				}, {
					X: touchMoveX,
					Y: touchMoveY
				});
				this.list.data.forEach((v, i) => {
					v.isTouchMove = false
					//滑动超过30度角 return
					if (Math.abs(angle) > 30) return;
					if (i == index) {
						if (touchMoveX > startX) //右滑
							v.isTouchMove = false
						else //左滑
							v.isTouchMove = true
					}
				})
			},
			/**
			 * 计算滑动角度
			 * @param {Object} start 起点坐标
			 * @param {Object} end 终点坐标
			 */
			angle(start, end) {
				var _X = end.X - start.X,
					_Y = end.Y - start.Y
				//返回角度 /Math.atan()返回数字的反正切值
				return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
			},
		}
	}
</script>


<style lang="scss">
	.user-coupon-list {
		.iconshaixuanxia-1 {
			font-size: 20rpx;
			transform: scale(0.6);
			color: #CDCDCD
		}


		.list-item {
			height: 190rpx;
			margin: 20rpx 25rpx 0 25rpx;
			border-radius: 18rpx;

			.bg {
				opacity: 0.1;
				border-radius: 18rpx;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				z-index: 1;
			}


			.item-title {
				top: 0;
				left: 0;
				width: 100rpx;
				padding: 4rpx 0;
				font-size: 20rpx;
				background: linear-gradient(235deg, #FF9E6C 0%, #FF5844 100%);
				border-radius: 16rpx 0 16rpx 0;
				z-index: 3;
			}

			.item-title.underline {
				background: linear-gradient(235deg, #FF9E6C 0%, #FF447F 100%);
			}

			.item-status {
				top: 0;
				right: 0;
				width: 90rpx;
				padding: 3rpx 0;
				font-size: 20rpx;
				z-index: 3;

				.bg {
					opacity: 0.1;
					border-radius: 0 16rpx 0 16rpx;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					z-index: 1;
				}
			}

			.item-icon {
				font-size: 120rpx;
				right: 0;
				bottom: -2rpx;
			}

			.item-price {
				width: 200rpx;
				height: 190rpx;
				border-radius: 18rpx;
				overflow: hidden;

				.dot-item {
					width: 24rpx;
					height: 24rpx;
					top: 83rpx;
				}

				.dot-item.left {
					left: -12rpx;
				}

				.dot-item.right {
					right: -12rpx;
				}
			}

			.iconxiangxiazhankai {
				transform: scale(0.8);
			}

			.use-btn {
				width: 116rpx;
				height: 56rpx;
				transform: rotateZ(360deg);
			}

			.can-gift {
				width: 116rpx;
				height: 34rpx;
				margin-top: 16rpx;
			}
		}


		.movable-area {
			width: calc(100% - 50rpx);
			height: 190rpx;
			margin: 20rpx 25rpx 0 25rpx;
			border-radius: 18rpx;
			overflow: hidden;

			.movable-view {
				width: 100%;
				height: 100%;

				.touch-item {
					display: flex;
					justify-content: space-between;
					width: 100%;
					height: 100%;
					overflow: hidden;

					.list-item {
						width: 100%;
						margin: 0 0 0 -180rpx;
						box-sizing: border-box;
						-webkit-transition: all 0.4s;
						transition: all 0.4s;
						-webkit-transform: translateX(180rpx);
						transform: translateX(180rpx);
						overflow: hidden;
					}

					.delete-btn {
						width: 180rpx;
						-webkit-transform: translateX(180rpx);
						transform: translateX(180rpx);
						-webkit-transition: all 0.4s;
						transition: all 0.4s;
						background: #f12c20;
					}
				}

				.touch-move-active .list-item,
				.touch-move-active .delete-btn {
					-webkit-transform: translateX(0);
					transform: translateX(0);
				}
			}

		}

		.search-popup {
			width: 100%;
			padding: 0 30rpx 50rpx 30rpx;

			.title {
				font-size: 32rpx;
				color: #19293F;
			}

			.search-item {
				width: 120rpx;
				height: 58rpx;
				background: #F5F5F5;
				border-radius: 8rpx;
			}

			.search-item.abs {
				top: 0;
				left: 0;
				opacity: 0.1;
			}

			.search-item:nth-child(5n) {
				margin-right: 0;
			}

			.search-btn {
				width: 260rpx;
				height: 72rpx;
				border-radius: 15rpx;
				border: 1rpx solid #C7C7C7;
				transform: rotateZ(360deg);
			}
		}

	}
</style>